import { SERVICE_API } from "@/components/CommonConstants"
import { RoleModel } from "@/components/model"
import DebounceSelect from "@/components/select/DebounceSelect"
import useRpcApi from "@/hooks/useRpcApiHook"
import { PlusOutlined } from "@ant-design/icons"
import { ActionType, EditableProTable, ProColumns, ProForm, ProTable } from "@ant-design/pro-components"
import { Alert, Button, Form, FormInstance, Modal, Popconfirm, Select, Spin, Switch } from "antd"
import { randomUUID } from "crypto"
import { useEffect, useRef, useState } from "react"

interface RolePermisModalProps {
    open: boolean
    role: RoleModel
    handleCancel: () => void
    handleOk: () => void
}

type PageItem = {
    id: number,
    res_code: string,
    res_name: string,
    res_type: string,
    res_description: string,
    create_time: string,
}

interface SelectOption {
    label: string;
    value: string;
}

interface AddEditRecordModalProps {
    open: boolean
    role: RoleModel
    handleCancel: () => void
    handleOk: () => void
}
function AddEditRecordModal({ open, role, handleCancel, handleOk }: AddEditRecordModalProps) {

    const { pageQuery, apiRpc } = useRpcApi()
    // Usage of DebounceSelect


    const [value, setValue] = useState<string[]>([]);
    const [options, setOptions] = useState<SelectOption[]>([]);

    useEffect(() => {
        setValue([])
        if (open) {
            fetchResourceQueryPage("")
        }
    }, [open])

    function fetchResourceQueryPage(res_name: string) {

        pageQuery(SERVICE_API.RESOURCE_QUERY_PAGE, 1, 20, {
            "res_name": res_name,
            "role_not": role.role_code,
        })
            .then(res => {
                console.log(`res length= ${res.data.length}`)
                return res
            })
            .then(res => res.data.map(row => {
                return {
                    label: row.res_name,
                    value: row.res_code
                }
            }))
            .then(options => setOptions(options))
    }


    function bindRole(roleCode: string, resCodes: string[]) {
        apiRpc(SERVICE_API.RESOURCE_ROLE_BIND, {
            role_code: roleCode,
            res_codes: resCodes
        })
            .then((_res) => {
                handleOk()
            })
            ;
    }


    return (
        <Modal title="资源设置" open={open} width={600} footer={null} onCancel={handleCancel} >
            <ProForm onFinish={async () => bindRole(role.role_code, value)}
                submitter={{
                    render: (props, _) => {
                        return [
                            <Button type="primary" onClick={() => props.form?.submit?.()}>提交</Button>,
                            <Button onClick={() => handleCancel()}>关闭</Button>,
                        ];
                    },
                }}
            >
                {/* 管理角色下拉框 */}
                <Form.Item valuePropName="checked">
                    <Select
                        showSearch
                        mode="multiple"
                        value={value}
                        placeholder="搜索"
                        defaultActiveFirstOption={false}
                        suffixIcon={null}
                        filterOption={false}
                        notFoundContent={null}
                        onSearch={fetchResourceQueryPage}
                        onChange={setValue}
                        options={options as SelectOption[]}
                    />
                </Form.Item>
                {options.length == 0 ?
                    <Form.Item>
                        <Alert message="无更多未关联权限" type="warning" showIcon />
                    </Form.Item>
                    : ""}

            </ProForm>

        </Modal >
    )
}

function RolePermisModal({
    open,
    role,
    handleCancel,
    handleOk,
}: RolePermisModalProps) {

    const actionRef = useRef<ActionType>()
    const formRef = useRef<FormInstance>()
    const { pageQuery, apiRpc } = useRpcApi()
    const [showAddRecordModal, setShowAddRecordModal] = useState(false);

    useEffect(() => {
        if (open) {
            actionRef?.current?.reload()
        }
    }, [open])

    // 定义表格列
    const columns: ProColumns<PageItem>[] = [
        {
            title: "资源编码",
            dataIndex: "res_code",
            key: "res_code",
            width: "15%",
            ellipsis: true,
        },
        {
            title: "资源名称",
            dataIndex: "res_name",
            key: "res_name",
            width: "15%",
            ellipsis: true,
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '此项为必填项',
                    },
                ],
            },
        },
        {
            title: "资源类型",
            dataIndex: "res_type",
            key: "res_type",
            width: "10%",
            ellipsis: true,
            search: false,
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '此项为必填项',
                    },
                ],
            },
            valueEnum: {
                service: "服务",
                menu: "菜单",
            },
        },
        {
            title: "创建时间",
            dataIndex: "create_time",
            key: "create_time",
            width: "10%",
            ellipsis: true,
            search: false,
            editable: false,
        },
        {
            title: "资源描述",
            dataIndex: "res_description",
            key: "res_description",
            width: "20%",
            ellipsis: true,
            search: false,
        },
        {
            title: "操作",
            valueType: "option",
            key: "option",
            width: "10%",
            render: (_dom, record, _id, action) => [
                <Popconfirm
                    title=""
                    description="删除此项?"
                    onConfirm={() => {
                        apiRpc(SERVICE_API.RESOURCE_ROLE_UNBIND, {
                            role_code: role.role_code,
                            res_codes: [record.res_code]
                        })
                            .then((_res) => {
                                actionRef?.current?.reload()
                            })
                    }}
                    onCancel={() => {
                        console.log(record, "   act  ", action)
                    }}
                    cancelText="取消"
                    okText="确定"
                >
                    <a>删除</a>
                </Popconfirm>,

            ],
        },
    ]

    const queryTableData = (params: any): Promise<any> => {
        const { current, pageSize } = params
        const _params = { ...params }
        _params["role_code"] = role.role_code
        delete _params.current
        delete _params.pageSize
        return pageQuery(SERVICE_API.RESOURCE_ROLE_REL_PAGE, current, pageSize, _params)
    }

    function onCancel() {
        handleCancel()
    }


    function onAddRow(row: PageItem) {
        console.log("新增记录", row)
    }



    return (
        <Modal title={`[${role.role_name}]资源设置`} open={open} width={1200} footer={null} onCancel={onCancel}>
            <AddEditRecordModal open={showAddRecordModal}
                role={role}
                handleCancel={() => setShowAddRecordModal(false)}
                handleOk={() => {
                    setShowAddRecordModal(false)
                    actionRef?.current?.reload()
                }}
            />
            <div>
                <ProTable<PageItem>
                    actionRef={actionRef}
                    cardBordered
                    formRef={formRef}
                    rowKey={"id"}
                    scroll={{
                        x: "max-content",
                        y: "calc(100vh - 400px)",
                    }}
                    bordered
                    form={{}}
                    columns={columns}
                    size={"small"}
                    request={params => queryTableData(params)}
                    postData={
                        (rows: PageItem[]) => rows.map(row => {
                            row.create_time = row.create_time.substring(0, 10)
                            return row
                        })
                    }
                    toolBarRender={() => [
                        <Button key="primary" type="primary" onClick={() => {
                            setShowAddRecordModal(true)
                        }}>
                            <PlusOutlined />
                            新建
                        </Button>,
                    ]}
                >

                </ProTable>
            </div>
        </Modal>
    )
}

export default RolePermisModal;
export type { RolePermisModalProps }